﻿using System;
using System.Collections.Generic;
using System.Globalization;
#if NET35
using System.Linq;
#endif
using System.Runtime.CompilerServices;
using System.Text;


namespace XoLib.Convertion
{
    /// <summary>
    /// static class to extend convertion
    /// </summary>
    static public class Extention
    {

        /// <summary>
        /// <para>
        /// <param name="text">string</param>
        /// </para>
        /// Add the method To to string
        /// <example> "145".To int() </example>/// 
        /// <returns>TResult</returns>
        /// </summary>
#if  NET45
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
#if NET35
        public static TResult To<TResult>(this string text)
#else
        public static TResult To<TResult>(string text)
#endif
        {
            return (TResult)Convert.ChangeType(text, typeof(TResult), CultureInfo.InvariantCulture);
        }


        /// <summary>
        /// <para>
        /// <param name="value">object</param>
        /// </para>
        /// Add the method ToOrDefault to object Nullable
        /// <example> "145".ToOrDefault int() </example>/// 
        /// <returns>TResult</returns>
        /// </summary>
#if  NET45
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
#if NET35
        public static T? ToOrDefault<T>(this object value)
#else
        public static T? ToOrDefault<T>( object value)
#endif        
            where T : struct, IConvertible
        {
            var x = value as T?;
            if (x.HasValue)
            {
                return x;
            }
            if (value == null || Convert.IsDBNull(value))
            {
                return null;
            }
            try
            {
                return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
            }
            catch (InvalidCastException)
            {
            }
            catch (FormatException)
            {
            }
            catch (OverflowException)
            {
            }
            catch (ArgumentException)
            {
            }
            return default(T?);
        }

    }

}
